package org.openarchitectureware.seman.asconnector;

import java.io.IOException;
import java.util.Collections;

import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.openarchitectureware.workflow.WorkflowInterruptedException;

public class EcoreReader {

	private static ResourceSet resourceSet = new ResourceSetImpl();

	public static Object loadFirstElementOnly(final String uri) {
		return load(resourceSet, uri, true);

	}

	public static Object load(final ResourceSet resourceSet, final String uri, final boolean firstElementOnly) {
		final Resource res = resourceSet.getResource(URI.createURI(uri), true);
		if (res == null) {
			throw new WorkflowInterruptedException("Couldn't find resource under " + uri);
		}
		try {
			if (!res.isLoaded()) {
				res.load(Collections.EMPTY_MAP);
			}
		} catch (final IOException e) {
			throw new WorkflowInterruptedException("Couldn't find resource under " + uri + " : " + e.getMessage());
		}
		final EList result = res.getContents();
		if (firstElementOnly) {
			if (result.isEmpty()) {
				return null;
			}
			return result.iterator().next();
		} else {
			return result;
		}
	}

}
